package com.quectel.cms.controller.securitypatrol;


import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.core.workorder.WorkOrderConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.dept.dto.DeptPersonDto;
import com.quectel.core.module.dept.service.DeptPersonService;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolEventReportDto;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolTaskRouteDto;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolDeviceSubjectService;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolEventReportService;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolSubjectService;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolTaskRouteService;
import com.quectel.core.module.workorder.dto.WorkOrderLogDto;
import com.quectel.sys.module.sys.dto.SysUserDto;
import com.quectel.sys.module.sys.service.SysUserService;
import com.quectel.util.common.*;
import com.quectel.util.kit.PageFetchKit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/05/07 14:10
 */
@RestController
@RequestMapping("securityPatrolEventReport")
@Tag(name = "SecurityPatrolEventReportController", description = "安保巡逻事件上报相关api")
public class SecurityPatrolEventReportController extends BaseController {

    @DubboReference
    private SecurityPatrolEventReportService securityPatrolEventReportService;
    @DubboReference
    private DeptPersonService deptPersonService;
    @DubboReference
    private SysUserService sysUserService;
    @DubboReference
    private SecurityPatrolDeviceSubjectService securityPatrolDeviceSubjectService;
    @DubboReference
    private SecurityPatrolSubjectService securityPatrolSubjectService;
    @DubboReference
    private SecurityPatrolTaskRouteService securityPatrolTaskRouteService;

    private static final String STATUS_NOT_NULL = "statusNotNull";

    @GetMapping("exportExcel")
    @RequirePermissions(values = "devicePatrolEventReport:exportExcel")
    @Log(express = "导出巡检任务详情")
    @Operation(summary = "安保巡逻事件任务导出")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        request.put(STATUS_NOT_NULL, STATUS_NOT_NULL);

        List<SecurityPatrolEventReportDto> result = PageFetchKit.fetchAll(reqParams -> securityPatrolEventReportService.queryList(reqParams), request.getParams(), 500);

        String[] headers = new String[]{"所属小区", "任务名称", "设备IMEI", "设备名称", "设备地址", "巡检照片", "巡检描述", "巡检结果", "跳检原因", "工单编号", "巡检人", "巡检时间"};
        List<String[]> dataList = new ArrayList<>();
        for (SecurityPatrolEventReportDto data : result) {
            String[] item = new String[headers.length];
            item[0] = data.getVillageName();
            item[1] = data.getTaskName();
            item[2] = data.getDeviceDto().getImei();
            item[3] = data.getDeviceDto().getName();
            item[4] = data.getDeviceDto().getInstallAddress();
            item[5] = data.getSnapshotImg();
            item[6] = data.getDetail();
            item[7] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PATROL_STATUS, String.valueOf(data.getStatus()));
            item[8] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.REASONS_FOR_SKIP_INSPECTION, String.valueOf(data.getSkipCheckReasonType()));
            item[9] = data.getWorkOrderNo();
            item[10] = data.getReportUsername();
            item[11] = data.getCompleteTime() != null ? DateUtils.format(data.getCompleteTime(), DateUtils.FormatType.COMMON) : null;
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "巡检记录", headers, dataList, "巡检记录");

    }

    @GetMapping("queryEventReportListBySomeCols")
    @RequirePermissions(values = "securityPatrolEventReport:list")
    @Operation(summary = "根据taskRouteId查询安保巡逻事件上报记录列表")
    public Response<List<SecurityPatrolEventReportDto>> list(@RequestParam Long taskId,
                                                             @RequestParam Long deviceId) {
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        SecurityPatrolTaskRouteDto securityPatrolTaskRouteDto = securityPatrolTaskRouteService.selectOne(taskId, deviceId);

        request.put(LambdaUtil.getFieldName(SecurityPatrolEventReportDto::getTaskRouteId), securityPatrolTaskRouteDto.getId());
        int total = securityPatrolEventReportService.queryTotal(request.getParams());

        List<SecurityPatrolEventReportDto> list = null;
        // 查询点位的上报记录,点位的记录只会全部项目都上报或者都没上报
        if (total > 0) {
            list = securityPatrolEventReportService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }
        return Response.<List<SecurityPatrolEventReportDto>>ok().wrap(list);
    }

    /**
     * 安保巡逻事件上报记录查询分页列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "securityPatrolEventReport:list")
    @Operation(summary = "安保巡逻事件上报记录查询分页列表")
    public Response<Page<SecurityPatrolEventReportDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        request.put(STATUS_NOT_NULL, STATUS_NOT_NULL);
        super.fillAuthorityData(request.getParams());
        int total = securityPatrolEventReportService.queryTotal(request.getParams());

        List<SecurityPatrolEventReportDto> list = null;
        if (total > 0) {
            list = securityPatrolEventReportService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<SecurityPatrolEventReportDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<SecurityPatrolEventReportDto>>ok().wrap(page);
    }


    /**
     * 查询安保巡逻事件上报单条记录
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "securityPatrolEventReport:edit")
    @Operation(summary = "查询安保巡逻事件上报单条记录")
    public Response<SecurityPatrolEventReportDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (securityPatrolEventReportService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SecurityPatrolEventReportDto securityPatrolEventReportDto = securityPatrolEventReportService.selectById(id);
        List<WorkOrderLogDto> workOrderLogDtos = securityPatrolEventReportDto.getWorkOrderLogDtos();
        if (workOrderLogDtos == null) {
            workOrderLogDtos = new ArrayList<>();
        } else {
            for (int j = 0; j < workOrderLogDtos.size(); j++) {
                WorkOrderLogDto workOrderLogDto = workOrderLogDtos.get(j);
                // 员工 2
                if (workOrderLogDto.getHandlerType().equals(WorkOrderConstants.ORDER_HANDLER_TYPE_DEPT_PERSON)) {
                    DeptPersonDto deptPersonDto = deptPersonService.selectById(workOrderLogDto.getHandlerId());
                    if (deptPersonDto == null) {
                        return Response.error("员工不存在");
                    }
                    workOrderLogDto.setHandlerUsername(DesensitizedUtil.chineseName(deptPersonDto.getName()));
                    workOrderLogDto.setHandlerMobile(DesensitizedUtil.mobilePhone(deptPersonDto.getMobile()));
                }
                // 管理员 1
                if (workOrderLogDto.getHandlerType().equals(WorkOrderConstants.ORDER_HANDLER_TYPE_ADMIN)) {
                    SysUserDto sysUserDto = sysUserService.selectById(workOrderLogDto.getHandlerId());
                    if (sysUserDto == null) {
                        return Response.error("管理员不存在");
                    }
                    workOrderLogDto.setHandlerUsername(DesensitizedUtil.chineseName(sysUserDto.getUsername()));
                    workOrderLogDto.setHandlerMobile(DesensitizedUtil.mobilePhone(sysUserDto.getMobile()));
                }
            }
        }

        return Response.<SecurityPatrolEventReportDto>ok().wrap(securityPatrolEventReportDto);
    }

    /**
     * 根据id查询安保巡逻事件上报单条记录
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "securityPatrolEventReport:info")
    @Operation(summary = "根据id查询安保巡逻事件上报单条记录")
    public Response<SecurityPatrolEventReportDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (securityPatrolEventReportService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SecurityPatrolEventReportDto securityPatrolEventReportDto = securityPatrolEventReportService.selectById(id);

        return Response.<SecurityPatrolEventReportDto>ok().wrap((securityPatrolEventReportDto));
    }

    /**
     * 保存安保巡逻事件上报单条记录
     */
    @PostMapping("save")
    @RequirePermissions(values = "securityPatrolEventReport:edit")
    @Operation(summary = "保存安保巡逻事件上报单条记录")
    public Response<Object> save(@RequestBody @Validated SecurityPatrolEventReportDto securityPatrolEventReportDto) {

        //填充基础数据
        fillSaveCommonData(securityPatrolEventReportDto);

        securityPatrolEventReportService.save(securityPatrolEventReportDto);

        return Response.ok();
    }

    /**
     * 修改安保巡逻事件上报单条记录
     */
    @PostMapping("update")
    @RequirePermissions(values = "securityPatrolEventReport:edit")
    @Operation(summary = "修改安保巡逻事件上报单条记录")
    public Response<Object> update(@RequestBody @Validated SecurityPatrolEventReportDto securityPatrolEventReportDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(securityPatrolEventReportDto.getId()));
        if (securityPatrolEventReportService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(securityPatrolEventReportDto);

        securityPatrolEventReportService.updateById(securityPatrolEventReportDto);

        return Response.ok();
    }

    /**
     * 批量删除安保巡逻事件上报单条记录
     */
    @PostMapping("delete")
    @RequirePermissions(values = "securityPatrolEventReport:delete")
    @Operation(summary = "批量删除安保巡逻事件上报单条记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (securityPatrolEventReportService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        securityPatrolEventReportService.deleteBatch(ids);

        return Response.ok();
    }
}
